import { defineStore } from 'pinia'
import {
  store,
  storageLocal,
  responsiveStorageNameSpace,
  getConfig
} from '../util'

export const useThemeStore = defineStore('easy-theme', {
  state: () => ({
    layout: storageLocal().getItem<StorageConfigs>(
      `${responsiveStorageNameSpace()}layout`
    ),
    locale:
      (storageLocal().getItem<StorageConfigs>(
        `${responsiveStorageNameSpace()}locale`
      )?.locale as string) ?? (getConfig() as string)
  }),
  getters: {
    getEpThemeColor(state) {
      return state.layout.epThemeColor
    }
  },
  actions: {
    /**
     * 设置主题
     * @param args  参数可以是一个数组，也可以是一个键值对对象
     * @param (key, value)
     * @parameter（[[key, value]]）
     */
    setTheme(...args: any[]): void {
      const storageKey = `${responsiveStorageNameSpace()}layout`

      if (args.length === 1 && Array.isArray(args[0])) {
        // 处理数组情况
        const entries = args[0]
        entries.forEach(([key, val]) => {
          this.layout[key] = val
        })
      } else if (args.length === 2) {
        // 处理单个 key, val 情况
        const [key, val] = args
        this.layout[key] = val
      } else {
        throw new Error('Invalid arguments for setTheme function')
      }

      // 将更新后的布局保存到 localStorage
      storageLocal().setItem(storageKey, this.layout)
    },
    /**
     * 设置语言
     * @param locale string zh en
     */
    setLocale(locale: string): void {
      this.locale = locale
      storageLocal().setItem(`${responsiveStorageNameSpace()}locale`, {
        locale: this.locale
      })
    }
  }
})

export function useThemeStoreHook() {
  return useThemeStore(store)
}
